<template>
  <ModelDetailDrawerLayout
    v-model:visible="drawerVisible"
    :title="props.title"
    :modelDetail="props.modelDetail"
    stage="SUPPLY_CHAIN_STAGE"
  >
    <CPageTable
      v-loading="backLoading"
      class="product-bom-drawer-page-table"
      :class="{ 'check-wrap': showBatch }"
      @register="registerPage"
      v-model:searchForm="searchForm"
      v-if="drawerVisible"
    >
      <template #headerRightButton>
        <div class="g-flex-center-center">
          <el-button
            @click="batchHandleConfirm"
            :loading="batchLoading"
            :disabled="totalCount == 0"
            v-btnPermission="'PCF_MODEL_BOM_EDIT'"
            >批量追溯
            <!-- {{ showBatch ? '追溯选中' : '批量追溯'
            }}{{ multipleSelectionLength > 0 ? `(${multipleSelectionLength})` : '' }} -->
          </el-button>
          <template v-if="totalCount > 0">
            <el-button
              type="default"
              @click="handleClearData"
              :loading="clearLoading"
              v-btnPermission="'PCF_MODEL_BOM_EDIT'"
              ><CIcon class="g-mr4" type="c-xian-qingkong"></CIcon>清空数据</el-button
            >

            <el-button type="primary" @click="handleExport" v-btnPermission="'PCF_MODEL_BOM_EDIT'">
              <CIcon class="g-mr4" type="c-xian-xiazai"></CIcon>
              下载BOM清单</el-button
            >
          </template>

          <template v-else>
            <el-button type="default" @click="handleDownloadTemplate">
              <CIcon class="g-mr4" type="c-xian-xiazai"></CIcon>
              下载模板</el-button
            >
            <g-upload
              :action="importModelBomAction"
              ref="uploadRef"
              :show-file-list="false"
              :limit="100"
              name="fileInfo"
              :post-params="{ modelNo }"
              accept=".xlsx, .xls"
              @success="handleUploadSuccess"
              style="margin: 0 12px"
              v-btnPermission="'PCF_MODEL_BOM_EDIT'"
            >
              <template #default="{ loading: btnLoading }">
                <el-button type="primary" :loading="btnLoading"
                  ><CIcon type="c-xian-daoru" class="g-mr4"></CIcon>导入产品BOM</el-button
                >
              </template>
            </g-upload>
            <el-button
              type="primary"
              @click="pcrHandle"
              v-btnPermission="'PCF_MODEL_BOM_EDIT'"
              v-if="
                props.modelDetail?.standard == StandardEnum.COMMERCIAL_VEHICLE_PCR ||
                props.modelDetail?.standard == StandardEnum.PASSENGER_VEHICLE_PCR
              "
            >
              <CIcon class="g-mr4" type="c-xian-daoru"></CIcon>
              按PCR填充
            </el-button>
            <el-button
              :disabled="!bomCount"
              type="primary"
              @click="handleLoadBom"
              :loading="fetchLoading"
              v-btnPermission="'PCF_MODEL_BOM_EDIT'"
              v-if="isShowLoadBtn"
            >
              <CIcon class="g-mr4" type="c-xian-daoru"></CIcon>
              加载BOM({{ bomCount }})
            </el-button>
            <CProgressButton
              class="g-ml12"
              text="已加载BOM："
              :refresh-status-fn="getRefreshStatusFn"
              @success="handleProgressButtonUploadSuccess"
              ref="progressRef"
            ></CProgressButton>
          </template>
        </div>
      </template>
      <vxe-column
        :show-overflow="false"
        field="nodeName"
        :minWidth="300"
        title="物料名称/物料编码"
        :filters="nodeNameFilterOptions"
        tree-node
      >
        <template #default="scope">
          <p
            v-ellTooltip
            class="c-table-column__main-text"
            :class="{ 'is-filter': isIncludingSearch(scope.row) }"
            >{{ scope.row.nodeName }}
          </p>
          <p v-ellTooltip class="c-table-column__sub-text">{{ scope.row.nodeCode }}</p>
          <!-- <CTableColumn
            :main-text="scope.row.nodeName"
            :sub-text="scope.row.nodeCode"
          ></CTableColumn> -->
        </template>
      </vxe-column>
      <template #dosageSlot="{ scope }">
        {{
          scope.row.unit == 'pcs'
            ? 'pcs'
            : scope.row.dosage
            ? scope.row.dosage + scope.row.unit
            : '-'
        }}
      </template>
      <template #weightSlot="{ scope }">
        <span v-if="isWeightUnit(scope.row.unit)">-</span>
        <span v-else>{{ scope.row.weight ? scope.row.weight + scope.row.weightUnit : '-' }}</span>
      </template>
      <template #supplierSlot="{ scope }">
        <CTableColumn :main-text="scope.row.supplierName" :sub-text="scope.row.supplierCode">
          <template #mainTextLeft>
            <el-tooltip
              content="已追溯，待供应商反馈"
              placement="top"
              v-if="scope.row.dataSource === DataSourceEnum.SUPPLIER"
            >
              <CIcon
                type="c-mian-jinggao"
                class="g-flex-shrink-0 g-mr4"
                style="color: #e1b205"
              ></CIcon>
            </el-tooltip>
            <el-tooltip
              content="追溯请求处理中，刷新列表查看结果"
              placement="top"
              v-else-if="scope.row.dataSource == DataSourceEnum.REQUEST_PROCESSING"
            >
              <CIcon
                type="c-mian-dengdai"
                class="g-flex-shrink-0 g-mr4"
                style="color: #4fbaf3"
              ></CIcon>
            </el-tooltip>
          </template>
        </CTableColumn>
      </template>
      <template #dataSlot="{ scope }">
        <CLink
          @click="handleOpenSiteDataDialog(scope.row)"
          v-if="
            scope.row.dataSource === DataSourceEnum.MODEL ||
            scope.row.dataSource === DataSourceEnum.SUPPLIER_FACTOR ||
            scope.row.dataSource === DataSourceEnum.SUPPLIER_MANUFACTURE
          "
          >查看</CLink
        >
        <span v-else>-</span>
      </template>
      <template #empty>
        <div class="empty">
          <img src="@/assets/images/empty-img.png" class="empty-img" />
          <p class="g-font-14n3 g-mb12">暂无数据，您可选择新增单条物料</p>
          <el-button @click="handleAddMaterial(nodeItem, 'peer')"
            ><CIcon type="c-xian-xinjian" class="g-mr4"></CIcon>新增物料</el-button
          >
        </div>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" :showMoreNum="1" />
      </template>
    </CPageTable>
    <ReplaceDialog
      v-model:visible="dialogVisible"
      :modelNo="props.modelNo"
      :supplierNo="selectSupplierNo"
      :nodeNo="nodeNo"
      :type="seeType"
      :partCode="selectCode"
      @refresh="handleRefreshChild($event, true)"
    ></ReplaceDialog>
    <SiteDataDialog
      :title="siteDataDialogTitle"
      v-model:visible="siteDataDialogVisible"
      readonly
      :type="seeType"
      :modelNo="nodeNo"
      :nodeNo="nodeNo"
      :nodeCode="nodeCode"
    ></SiteDataDialog>
    <!-- 编辑物料 --- 弹出层 -->
    <MaterialDialog
      v-model:visible="materialDialogVisible"
      :enterpriseNo="props.modelDetail?.enterpriseNo"
      :nodeNo="nodeNo"
      :modelNo="props.modelNo"
      :nodeItem="materialDialogNodeItem"
      :addType="addType"
      @refresh="handleEditRefresh"
      @strong-refresh="handleRefreshChild($event, false)"
      @expand-refresh="handleRefreshChild($event, true)"
      @load-bom-count="loadBomCount"
      @refresh-and-clear="refreshAndClear"
    ></MaterialDialog>
    <BackToSupplier
      v-model:visible="backToSupplierDialogVisible"
      :nodeNo="nodeNo"
      :modelNo="props.modelNo"
      :modelDetail="props.modelDetail"
      :node="selectNode"
      @refresh="handleRefreshChild"
    ></BackToSupplier>
    <SupplierFactorDialog
      v-model:visible="supplierFactorDialogVisible"
      :nodeNo="nodeNo"
      :formNo="props.modelNo"
      readonly
      :title="supplierDialogTitle"
      :nodeCode="nodeCode"
      @refresh="handleEditRefresh"
    ></SupplierFactorDialog>
    <ReplaceLowCarbonMaterialDialog
      v-model:visible="replaceLowCarbonMaterialVisible"
      :nodeNo="replaceLowCarbonMaterialNodeNo"
      :modelNo="props.modelNo"
      @refresh="handleRefreshChild($event, true)"
    />
  </ModelDetailDrawerLayout>
</template>

<script lang="ts" setup name="ProductBomDrawer">
import { defineProps, defineEmits, computed, reactive, Ref, ref, watch, nextTick } from 'vue';
import { CLink } from '@/components/CLink';
import {
  CPageTable,
  useCPageTable,
  SearchOptionsType,
  ColumnSettingTypeEnum,
  TableFieldsSettingType,
  CPageTableProps
} from '@/components/CPageTable';
import ReplaceDialog from './components/ReplaceDialog/index.vue';
import SiteDataDialog from './components/SiteDataDialog/index.vue';
import BackToSupplier from './components/BackToSupplier/index.vue';
import SupplierFactorDialog from './components/SupplierFactorDialog/index.vue';
import ReplaceLowCarbonMaterialDialog from './components/ReplaceLowCarbonMaterialDialog/index.vue';
import { MaterialDialog } from './components/MaterialDialog';
import ModelDetailDrawerLayout from '../ModelDetailDrawerLayout/index.vue';
import { useMessage } from '@/hooks/useMessage';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import type { TableButtonItem } from '@/components/CTable';
import { VxeTablePropTypes } from '@xfchenju/vxe-table';
import type { GetListBomTreeResult } from '@/apis/pcf/myModel/model/modelDetailModel';
import type { ModelDetailResult } from '@/apis/pcf/myModel/model/modelManage';
import {
  importModelBomAction,
  getListBomTree,
  deleteNode,
  postClearData,
  exportModelBom,
  loadBomData,
  getBomCount,
  getCountBomNum,
  loadBomDataByPcr,
  getBomProgress,
  createPartsModel,
  queryInfoAndChild,
  getNodeDetail,
  queryRootBom,
  queryChildBomByNo
} from '@/apis/pcf/myModel/modelDetail';
import { GUpload } from '@/components/GUpload';
import { CProgressButton } from '@/components/CProgressButton';
import { HTTP_RESPONSE_CODE } from '@/constants';
import { DataSourceEnum, ProcessStageCodeEnum, StandardEnum, DataSourceMap } from '@/constants/pcf';
import { useTemplateFile } from '@/hooks/useTemplateFile';
import { useExport } from '@/hooks/useExport';
import { isWeightUnit, empty, findItemInTree } from '@/utils';
import { getSupplierNo } from '@/apis/pcf/supplier/supplierList';
import { useBatch } from './useBatch';
interface ProductBomDrawerProps {
  title: string;
  subTitle: string;
  visible: boolean;
  modelNo: string;
  modelDetail?: ModelDetailResult;
}

const props = defineProps<ProductBomDrawerProps>();
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage, createConfirm } = useMessage();
const { handleDownloadTemplate } = useTemplateFile('BOM_IMPORT_TEMPLATE', 'model');
const { handleExportFile } = useExport();
const drawerVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
// watch(
//   () => drawerVisible.value,
//   val => {
//     if (val) {
//       loadBomCount();
//     }
//   }
// );
const nodeNameFilterOptions = ref([{ data: '', name: 'nodeName' }]);
const materialCategoryFilterOptions = ref([{ data: '', name: 'materialCategory' }]);
// const searchedFields = ref<string[]>([]);
const searchText = computed(() => {
  return {
    searchName: String(searchForm.searchName).trim().toLowerCase(),
    materialCategory: String(searchForm.materialCategory).trim().toLowerCase()
  };
});

const searchedFields = computed(() => {
  let res = [];
  if (String(searchForm.searchName).trim().toLowerCase()) {
    res.push('nodeName');
    res.push('nodeCode');
  }
  if (String(searchForm.materialCategory).trim().toLowerCase()) {
    res.push('materialCategory');
  }
  return res;
});

const isFilter = computed(() => {
  return !!searchedFields.value?.length;
});

const searchForm = reactive({
  searchName: '',
  materialCategory: ''
});

const searchOptions: SearchOptionsType[] = [
  {
    name: '物料编码或名称',
    field: 'searchName',
    type: 'input'
    // onSearchFormChange: (form: any) => {
    //   console.log('onSearchFormChange 物料编码或名称', form);
    //   searchEvent(form.searchName, ['nodeName', 'nodeCode'], true);
    // }
  },
  {
    name: '材料类别',
    field: 'materialCategory',
    type: 'input'
    // onSearchFormChange: (form: any) => {
    //   console.log('onSearchFormChange 材料类别或牌号', form);
    //   nextTick(() => {
    //     searchEvent(form.materialCategory, ['materialCategory'], true);
    //   });
    // }
  }
];

// 获取进度条进度
function getRefreshStatusFn(): Promise<{ current: number; total: number; refreshing: boolean }> {
  return new Promise(resolve => {
    getBomProgress(props.modelNo).then(res => {
      const data = {
        current: res.pullProgress,
        total: 1,
        refreshing: res.pullStatus === 'DOING' ? true : false
      };
      resolve(data);
    });
  });
}

const handleProgressButtonUploadSuccess = () => {
  createMessage.success('加载BOM完成！');
  handleRefresh();
};
const tableFieldsSetting: TableFieldsSettingType[] = [
  // {
  //   title: '物料名称/物料编码',
  //   field: 'nodeName',
  //   slot: 'nodeNameSlot',
  //   minWidth: 300,
  //   columnSettingConfig: {
  //     enabled: true,
  //     type: ColumnSettingTypeEnum.REQUIRED
  //   },
  //   treeNode: true,
  //   filters: nodeNameFilterOptions as any,
  //   filterMethod: filterAgeMethod as any,
  //   filterRecoverMethod: filterAgeRecoverMethod
  // },
  {
    title: '材料类别',
    field: 'materialCategory',
    minWidth: 140,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '数量',
    field: 'quantity',
    width: 70,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '单位用量',
    field: 'dosage',
    slot: 'dosageSlot',
    width: 120,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '物料供应商名称/编码',
    field: 'supplierName',
    overflow: false,
    slot: 'supplierSlot',
    minWidth: 170,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '场地数据',
    field: 'data',
    slot: 'dataSlot',
    width: 100,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '操作',
    field: 'op',
    slot: 'op',
    width: 120,
    // fixed: 'right',
    columnSettingConfig: {
      enabled: true,
      type: ColumnSettingTypeEnum.FIXED
    }
  }
];

const tableConfig = reactive({
  treeConfig: {
    transform: true,
    rowField: 'nodeNo',
    parentField: 'parentNodeNo',
    iconOpen: 'c-mian-xia iconfont',
    iconClose: 'c-mian-you iconfont',
    lazy: true,
    hasChild: 'hasChildren',
    loadMethod({ row }) {
      // 异步加载子节点

      return getListBomTree(props.modelNo, row.nodeNo).then(res => {
        if (searchForm.searchName || searchForm.materialCategory) {
          const params = {
            rootNodeNo: row.nodeNo,
            nameOrCode: searchForm.searchName,
            materialCategory: searchForm.materialCategory
          };
          return queryChildBomByNo(params).then(data => {
            const list = data.map(item => item.nodeNo);
            if (list.length) {
              return res.filter(item => list.includes(item.nodeNo));
            }
            return res;
          });
        } else {
          return res;
        }
      });
    }
  } as VxeTablePropTypes.TreeConfig
});
const options: CPageTableProps = {
  title: `${props.subTitle}(0)`,
  searchOptions,
  isTree: true,
  tableOptions: {
    pagination: false,
    loadData,
    border: true,
    extraTableOption: {
      expandConfig: { reserve: true },
      treeConfig: tableConfig.treeConfig,
      checkboxConfig: {
        checkField: 'checked', // 避免多数据时全选卡顿
        trigger: 'row',
        checkMethod: ({ row }: { row: GetListBomTreeResult }) => {
          return row.parentNodeNo == '-1' && showBatch.value;
        }
      },
      scrollY: { enabled: true, gt: 50, oSize: 30, rSize: 50 }, // gt50数量超过50开启虚拟滚动
      maxHeight: '100%',
      rowConfig: { height: 56, keyField: 'nodeNo' }
    },
    rowKey: 'nodeNo',
    cellHeightSize: 'small'
  },
  tableFieldsSetting,
  enableFieldsSetting: true
};
/**
 * 源BOM数据
 */
const sourceBomTree = ref<GetListBomTreeResult[]>([]);
const [
  registerPage,
  { refresh, setProps, searchEvent, clearData, operationTable, resetSelection }
] = useCPageTable(options);
const refreshAndClear = () => {
  operationTable((tableRef: Ref<any>) => {
    tableRef.value.clearTreeExpand();
    refresh();
  });
};
const { batchHandleConfirm, showBatch, batchLoading } = useBatch(
  refreshAndClear,
  props.modelNo,
  searchForm,
  sourceBomTree
);
const loading = ref(false);
/**
 * 是否已导入数据
 */
const isBomImported = ref(false);
const totalCount = ref(0);
// 更新标题
watch(
  () => totalCount.value,
  (count: number) => {
    setProps({
      title: `${props.subTitle}(${count})`
    });
    count ? (isBomImported.value = true) : (isBomImported.value = false);
  }
);
const tableData = ref([] as any[]);
const filterNameMethod = async (rootData: GetListBomTreeResult[]) => {
  let allArr: any[] = [];
  if (rootData.length) {
    const params = {
      rootNodeNo: rootData[0].nodeNo,
      nameOrCode: searchForm.searchName,
      materialCategory: searchForm.materialCategory
    };
    tableData.value = await queryChildBomByNo(params);
    const getParent = (child: any) => {
      // 递归向上查找父，直到parentNodeNo 为null为止
      const arr = tableData.value.filter(item => item.nodeNo == child.parentNodeNo);
      console.log('parent-arr', arr);
      if (arr.length) {
        allArr.unshift(arr[0]);
        getParent(arr[0]);
      }
    };
    //筛选出满足条件的所有列表
    allArr = tableData.value.filter(item => {
      return (
        item.nodeName.includes(searchForm.searchName.trim()) ||
        (item.nodeCode && item.nodeCode.includes(searchForm.searchName.trim()))
      );
    });
    if (allArr.length) {
      //然后取满足条件的第一个
      allArr = [allArr[0]];
      getParent(allArr[0]);
      // 数组去重
      const uniqueArray = allArr.filter(
        (obj, index, self) => index === self.findIndex(el => el.nodeNo === obj.nodeNo)
      );
      console.log('uniqueArray', uniqueArray);

      // 再次去重
      const uniqueArrayAgain = uniqueArray.filter(
        (obj, index, self) => index === self.findIndex(el => el.parentNodeNo === obj.parentNodeNo)
      );
      console.log('uniqueArrayAgain', uniqueArrayAgain);

      for (let i = 0; i < uniqueArray.length - 1; i++) {
        setTimeout(() => {
          operationTable((tableRef: Ref<any>) => {
            const list = tableRef.value?.getData() || [];
            const node = findItemInTree(
              list,
              (n: GetListBomTreeResult) => n.nodeNo === uniqueArray[i].nodeNo
            );
            console.log('list-node', node);
            nextTick(() => {
              node && tableRef.value.reloadTreeChilds(node);
            });
          });
        }, 50 + 850 * i);
      }
      rootData.shift();
      return uniqueArray.concat(rootData);
    }
  }
  return allArr;
};

/**
 * 加载数据
 */
let timer: any;
function loadData() {
  loadBomCount();
  if (searchForm.materialCategory || searchForm.searchName) {
    clearData();
    timer && clearTimeout(timer);
    const params = {
      modelNo: props.modelNo,
      nameOrCode: searchForm.searchName,
      materialCategory: searchForm.materialCategory
    };
    return queryRootBom(params).then(async res => {
      const allArr = await filterNameMethod(res);
      return {
        records: allArr,
        total: allArr?.length || 0
      };
    });
  } else {
    return getListBomTree(props.modelNo, '-1').then(res => {
      if (res.length) {
        isBomImported.value = true;
        res.forEach(item => {
          item.filtered = true;
        });
      } else {
        isBomImported.value = false;
      }
      sourceBomTree.value = res || [];
      return {
        records: res,
        total: res.length
      };
    });
  }
}

const selectSupplierNo = ref('');
/**
 * 配置表格的按钮
 * @param row 表格行数据
 */
function getTableButtonsConfig(row: GetListBomTreeResult): TableButtonItem[] {
  let arr: TableButtonItem[] = [
    {
      text: '编辑',
      btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleOpenMaterialDialog(row)
    }
  ];
  if (row.dataSource !== DataSourceEnum.SUPPLIER && (row.supplierName || row.supplierCode)) {
    let formData: TableButtonItem[] = [
      {
        text: '追溯供应商场地数据',
        btnPermission: 'PCF_PROCESS_DATA_EDIT',
        onClick: () => handleBackToSupplierData(row)
      }
    ];
    arr = arr.concat(formData);
  }
  if (row.supplierName) {
    let formData: TableButtonItem[] = [
      {
        text: '替换为供应商数据集',
        btnPermission: 'PCF_PROCESS_DATA_EDIT',
        onClick: () => handleReplaceSubModelData(row, 'SUPPLIER'),
        divided: row.dataSource !== DataSourceEnum.SUPPLIER
      }
    ];
    arr = arr.concat(formData);
  }
  const origArr: TableButtonItem[] = [
    {
      text: '新增同级物料',
      btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleAddMaterial(row, 'peer')
    },
    {
      text: '新增子级物料',
      btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleAddMaterial(row, 'child')
    },
    {
      text: '替换为子模型数据',
      btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleReplaceSubModelData(row, 'MODEL')
    },
    {
      text: '创建零部件子模型',
      // btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleCreateSubModel(row)
    },
    {
      text: '替换低碳材料',
      // btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => handleReplaceLowCarbonMaterial(row)
    },
    {
      text: '删除物料',
      btnPermission: 'PCF_PROCESS_DATA_DELETE',
      onClick: () => handleDeleteMaterial(row),
      divided: true
    }
  ];
  arr = arr.concat(origArr);
  return arr;
}

/**
 * 编辑物料
 */
const materialDialogVisible = ref(false);
const materialDialogNodeItem = ref<GetListBomTreeResult>();
function handleOpenMaterialDialog(row: GetListBomTreeResult) {
  nodeNo.value = row.nodeNo;
  addType.value = undefined;
  materialDialogNodeItem.value = row;
  materialDialogVisible.value = true;
}
/**
 * 新增同级/子级物料
 */
const addType = ref<'peer' | 'child'>();
const handleAddMaterial = (row: GetListBomTreeResult, type: 'peer' | 'child') => {
  nodeNo.value = '';
  addType.value = type;
  materialDialogNodeItem.value = row;
  materialDialogVisible.value = true;
};

const nodeItem: any = {
  parentNodeNo: '-1',
  modelNo: props.modelNo
};

const findParent = (row: GetListBomTreeResult, tableRef: Ref<any>) => {
  const dataAfter = tableRef.value?.getTableData().fullData;
  let result;
  function findItem(tree: any[], id: string): GetListBomTreeResult | null {
    for (var i = 0; i < tree.length; i++) {
      if (tree[i].nodeNo === id) {
        return tree[i];
      } else if (tree[i].children) {
        result = findItem(tree[i].children, id);
        if (result) {
          return result;
        }
      }
    }
    return null;
  }
  return findItem(dataAfter, row.parentNodeNo);
};
/**
 * 删除物料
 */
function handleDeleteMaterial(row: GetListBomTreeResult) {
  createConfirm('提示', '删除后不可恢复，是否继续？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      loading.value = true;
      await deleteNode(row.nodeNo);
      loading.value = false;
      createMessage.success('删除成功！');
      operationTable((tableRef: Ref<any>) => {
        tableRef.value?.remove(row);
        // 删除成功后 查找父级的是否还有children,没有的话则hasChildren置为false, 用来去掉箭头
        let parent = findParent(row, tableRef);
        if (parent && (!parent.children || parent.children.length == 0)) {
          parent.hasChildren = false;
          tableRef.value?.updateData({
            rowId: parent.nodeNo, // 这里的 'row_id' 是你想要更新的数据行的唯一标识，就是rowKey
            record: {
              hasChildren: false
            }
          });
        }
        nextTick(() => {
          loadBomCount();
          // handleCalculateCount(row.nodeNo, tableRef.value?.data);
        });
        showBatch.value = false;
      });
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  });
}

/**
 * 重新计算数量
 * @param nodeNo
 * @param data
 */
function handleCalculateCount(nodeNo: string, data: any[]) {
  const removeItem = data.find(n => n.nodeNo === nodeNo);
  totalCount.value = totalCount.value - (getTotalChildrenCount(removeItem?.children) + 1);
}

/**
 * 获取含子集的总数
 */
function getTotalChildrenCount(arr: any[]) {
  if (!arr?.length) return 0;
  let count = 0;
  for (let i = 0; i < arr.length; i++) {
    count++;
    if (arr[i]?.children?.length) {
      const resCount = getTotalChildrenCount(arr[i]?.children);
      count += resCount;
    }
  }
  return count;
}

const nodeNo = ref('');
const nodeCode = ref('');

/**
 * 替换为子模型或供应商数据集
 */
const dialogVisible = ref(false);
const selectCode = ref('');
function handleReplaceSubModelData(row: GetListBomTreeResult, type: 'SUPPLIER' | 'MODEL') {
  if (type === 'SUPPLIER') {
    checkSupplier(row)
      .then(({ supplierNo }) => {
        selectSupplierNo.value = supplierNo as string;
        selectCode.value = row.nodeCode;
        nodeNo.value = row.nodeNo;
        seeType.value = type;
        dialogVisible.value = true;
      })
      .catch(() => {
        // createMessage.error('供应商不存在，无法替换！');
      });
  } else {
    selectCode.value = '';
    nodeNo.value = row.nodeNo;
    seeType.value = type;
    dialogVisible.value = true;
  }
}

/**
 * 创建零部件子模型
 */
function handleCreateSubModel(row: GetListBomTreeResult) {
  createConfirm('提示', '是否创建零部件子模型?', {}).then(async () => {
    try {
      backLoading.value = true;
      await createPartsModel(props.modelNo, row.nodeNo);
      createMessage.success('创建成功');
      setTimeout(() => {
        backLoading.value = false;
        window.open('/myModel/partsModel');
      }, 350);
    } catch (error) {
      console.log('error', error);
      backLoading.value = false;
    }
  });
}

const replaceLowCarbonMaterialVisible = ref(false);
const replaceLowCarbonMaterialTempRow = ref<GetListBomTreeResult>();
const replaceLowCarbonMaterialNodeNo = ref('');
/**
 * 替换低碳材料
 */
function handleReplaceLowCarbonMaterial(row: GetListBomTreeResult) {
  replaceLowCarbonMaterialNodeNo.value = row.nodeNo;
  replaceLowCarbonMaterialVisible.value = true;
  replaceLowCarbonMaterialTempRow.value = row;
}

/**
 * 追溯供应商场地数据
 */
const backToSupplierDialogVisible = ref(false);
const selectNode = ref();
const backLoading = ref(false);
/**
 * 检查供应商编号是否存在
 * @param row
 */
const checkSupplier = (
  row: GetListBomTreeResult
): Promise<{
  supplierNo: string;
  supplierCode: string;
}> => {
  return new Promise((resolve, reject) => {
    backLoading.value = true;
    getSupplierNo(
      row.supplierName,
      props.modelDetail?.enterpriseNo as string,
      row.supplierCode || undefined
    )
      .then(res => {
        backLoading.value = false;

        if (res.supplierNo) {
          resolve({
            supplierNo: res.supplierNo,
            supplierCode: res.supplierCode
          });
        } else {
          reject('');
        }
      })
      .catch(() => {
        backLoading.value = false;
        reject('');
      });
  });
};
const handleBackToSupplierData = async (row: GetListBomTreeResult) => {
  checkSupplier(row)
    .then(({ supplierNo, supplierCode }) => {
      nodeNo.value = row.nodeNo;
      selectNode.value = row;
      selectNode.value.supplierNo = supplierNo;
      selectNode.value.supplierCode = supplierCode;
      backToSupplierDialogVisible.value = true;
    })
    .catch(() => {
      // createMessage.error('供应商不存在，无法追溯！');
    });
};

/**
 * 查看供应商场地因子
 */
const supplierFactorDialogVisible = ref(false);
/**
 * 查看场地数据
 */
const formNo = ref();
const siteDataDialogTitle = ref('');
const supplierDialogTitle = ref('');
const siteDataDialogVisible = ref(false);
const seeType = ref<'MODEL' | 'SUPPLIER' | undefined>('MODEL');
function handleOpenSiteDataDialog(row: GetListBomTreeResult) {
  if (row.dataSource == DataSourceEnum.SUPPLIER_FACTOR) {
    supplierFactorDialogVisible.value = true;
    nodeNo.value = row.nodeNo;
    nodeCode.value = '';
    siteDataDialogTitle.value = '';
  } else {
    siteDataDialogTitle.value = row.nodeName;
    seeType.value = row.dataSource == 'MODEL' ? 'MODEL' : 'SUPPLIER';
    nodeNo.value = row.nodeNo;
    nodeCode.value = row.nodeCode;
    siteDataDialogVisible.value = true;
  }
}

/**
 * 导入产品BOM
 */
const handleUploadSuccess = (file: any) => {
  if (file?.response?.code === HTTP_RESPONSE_CODE.OK_CODE) {
    createMessage.success('上传成功');
    handleRefresh();
  }
};
const pcrHandle = async () => {
  // 调用pcr填充接口
  try {
    await loadBomDataByPcr(props.modelDetail?.modelNo as string);
    createMessage.success('填充成功！');
    handleRefresh();
  } catch (e) {
    console.log('error', e);
  }
};

/**
 * 清空loading
 */
const clearLoading = ref(false);

/**
 * 清空模型数据
 */
function handleClearData() {
  createConfirm('提示', '清除后不可恢复，是否继续？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      clearLoading.value = true;
      await postClearData(props.modelNo);
      createMessage.success('清空成功！');
      clearLoading.value = false;
      // totalCount.value = 0;
      handleRefresh();
    } catch (error) {
      console.log('error', error);
      clearLoading.value = false;
    }
  });
}

/**
 * 刷新
 * @param keepSearch  是否保留搜索条件
 */
function handleRefresh(keepSearch?: boolean) {
  refresh();
  emits('refresh', ProcessStageCodeEnum.SUPPLY_CHAIN_STAGE);
  showBatch.value = false;
  resetSelection();
  if (!keepSearch) {
    searchForm.materialCategory = '';
    searchForm.searchName = '';
  } else {
    // if (searchForm.searchName) {
    //   searchEvent(searchForm.searchName, ['nodeName', 'nodeCode'], true);
    // }
    // if (searchForm.materialCategory) {
    //   searchEvent(searchForm.materialCategory, ['materialCategory'], true);
    // }
  }
}
/**
 * 刷新自己和子的数据
 */
const handleRefreshChild = (nodeNo: string, isExpand = false) => {
  const myNodeNo = nodeNo || replaceLowCarbonMaterialNodeNo.value;
  operationTable(async (tableRef: Ref<any>) => {
    const data = await queryInfoAndChild(props.modelDetail?.modelNo as string, myNodeNo);
    // 获取原数据
    const list = tableRef.value?.getData() || [];

    const node = findItemInTree(list, (n: GetListBomTreeResult) => n.nodeNo === myNodeNo);
    if (node) {
      // 更新数据数据
      Object.assign(node, {
        ...data[0]
      });
      // 如果设置展开为true, 重载子集
      if (isExpand) {
        tableRef.value.toggleTreeExpand(node, false);
        tableRef.value.reloadTreeChilds(node);
      }
      loadBomCount();

      resetSelection();
      emits('refresh', ProcessStageCodeEnum.SUPPLY_CHAIN_STAGE);
    }
  });
};

/**
 * 编辑刷新
 */
function handleEditRefresh(nodeNo: string) {
  if (nodeNo) {
    operationTable(async (tableRef: Ref<any>) => {
      const list = tableRef.value?.getData() || [];
      const data = await getNodeDetail(nodeNo);
      const node = findItemInTree(list, (n: GetListBomTreeResult) => n.nodeNo === nodeNo);
      // const node = list.find((n: GetListBomTreeResult) => n.nodeNo === row.nodeNo);
      console.log('node', node);
      if (node) {
        Object.assign(node, {
          ...data
        });
        showBatch.value = false;
      }
      resetSelection();
    });
  } else {
    handleRefresh();
  }
}

const bomCount = ref(0);
const fetchLoading = ref(false);

const isShowLoadBtn = ref(true);

const loadBomCount = () => {
  isShowLoadBtn.value = true;
  getCountBomNum(props.modelDetail?.modelNo as string).then(res => {
    totalCount.value = res || 0;
    if (totalCount.value == 0) {
      getBomCount(
        props.modelDetail?.modelCode as string,
        props.modelDetail?.enterpriseNo as string
      ).then(bomRes => {
        bomCount.value = bomRes || 0;
      });
    }
  });
};
// loadBomCount();
const progressRef = ref();
const handleLoadBom = async () => {
  //加载bom
  const params = {
    modelNo: props.modelDetail?.modelNo as string,
    productModel: props.modelDetail?.modelCode as string
  };
  fetchLoading.value = true;
  try {
    await loadBomData(params);
    isShowLoadBtn.value = false;
    progressRef.value?.startRefresh();

    // handleRefresh();
  } finally {
    fetchLoading.value = false;
  }
};
const handleExport = () => {
  handleExportFile(exportModelBom, props.modelNo);
};
const isIncludingSearch = (row: GetListBomTreeResult) => {
  if (searchForm.searchName || searchForm.materialCategory) {
    return (
      (searchForm.searchName.trim() &&
        row.nodeName &&
        row.nodeName.includes(searchForm.searchName.trim())) ||
      (searchForm.searchName && row.nodeCode && row.nodeCode == searchForm.searchName.trim()) ||
      (searchForm.materialCategory.trim() &&
        row.materialCategory &&
        row.materialCategory.includes(searchForm.materialCategory.trim()))
    );
  } else {
    return false;
  }
};
</script>

<style lang="scss" scoped>
.product-bom-drawer-page-table {
  :deep(.c-page-header) {
    .header-left__title {
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #0a1f33;
      line-height: 22px;
    }
  }
  :deep(.is--disabled.vxe-cell--checkbox) {
    cursor: auto;
  }
  :deep(.c-page-table__body) {
    height: calc(100vh - 80px - 56px - 32px);
    overflow-y: auto;
    overflow-x: hidden;
    .c-page-table__body-main {
      height: 100%;
    }
    .body-main__filter {
      padding: 16px 16px 12px;
      min-height: 60px;
      .filter-fixed-buttons {
        bottom: 12px;
      }
    }
    .body-main__table {
      padding: 0 16px;
      height: calc(100% - 60px);
      .vxe-tree--btn-wrapper {
        top: 4px;
        .vxe-tree--node-btn {
          color: #435970 !important;
        }
      }
      .vxe-cell--filter {
        display: none;
      }
    }
    .vxe-cell--checkbox {
      display: flex;
      align-items: baseline;
    }
    .vxe-body--row:not(.row--level-0) {
      .vxe-checkbox--icon {
        display: none;
      }
    }
    .vxe-header--row {
      .vxe-checkbox--icon {
        display: none;
      }
      .vxe-checkbox--label {
        color: #0a1f33;
      }
    }
    .vxe-body--row {
      .vxe-checkbox--icon {
        display: none;
      }
    }
  }
}
.check-wrap {
  :deep(.vxe-body--row.row--level-0) {
    .vxe-checkbox--icon {
      display: block !important;
    }
  }
  :deep(.vxe-header--row) {
    .vxe-checkbox--icon {
      display: block !important;
    }
  }
}

.c-table-column__main-text {
  width: 100%;
  font-size: 14px;
  font-weight: 400;
  color: #435970;
  line-height: 22px;
}
.c-table-column__sub-text {
  font-size: 12px;
  font-weight: 400;
  color: #7a8a99;
  line-height: 20px;
}
.is-filter {
  color: $themeColor;
}
.empty {
  padding-top: 47px;
  padding-bottom: 20px;
  .empty-img {
    width: 180px;
    height: 110px;
    margin-bottom: 9px;
  }
}
</style>
